import json, os
from selenium.webdriver.remote.webdriver import WebDriver

from loguru import logger


class SetCookies:

    def __init__(self, driver: WebDriver):
        self.driver = driver

    def save_cookies_to_file(self):
        """保存cookies到文件"""
        file_path = self.get_cookies_dir()
        cookies = self.driver.get_cookies()
        logger.info("save to cookies file：%s" % cookies)
        cookie_file = file_path + 'cookies'
        with open(cookie_file, 'w', encoding='utf-8') as f:
            json.dump(cookies, f)

    def get_cookies_dir(self):
        work_path = os.path.dirname(os.path.dirname(__file__))  # 获取当前的工作目录
        file_path = work_path + "/data/"
        if not os.path.exists(file_path):
            os.mkdir(file_path)
        return file_path

    def check_cookies(self):
        """检查cookies"""
        # 设置一个登陆状态，初始值未登陆
        login_status = False
        # 将cookies保存到driver中
        self.save_cookies_to_driver()

        # 通过连接检查登陆后的页面URL，判断是否登陆成功
        self.driver.get("https://mubu.com/app")
        # 获取当前的URL
        current_url = self.driver.current_url
        if current_url == "https://mubu.com/app":
            login_status = True
            logger.info("login success，cookies pass")

        else:
            login_status = False
            logger.info("login fail")
        return login_status

    def save_cookies_to_driver(self):
        """保存cookies信息到driver"""
        cookies_file = self.get_cookies_file()
        if not os.path.exists(cookies_file):
            with open(cookies_file, "w") as f:
                f.write("cookis")
        open_cookies_file = open(cookies_file, "r")
        read_cookies_info = open_cookies_file.readline()
        try:
            read_cookies_dict = json.loads(read_cookies_info)

            # 清除旧的cookies
            self.driver.get("https://mubu.com/login/password")
            self.driver.delete_all_cookies()

            # 添加cookies到driver
            for cookie in read_cookies_dict:
                if 'expiry' in cookie:
                    del cookie['expiry']
                self.driver.add_cookie(cookie)
            self.driver.get("https://mubu.com/app")
            return self.driver
        except Exception as e:
            return False

    def get_cookies_file(self):
        """获取cookies文件"""
        cookie_file = self.get_cookies_dir() + "cookies"
        return cookie_file


if __name__ == '__main__':
    pass
    # se = BaseDriver('chrome', url='https://www.jd.com').driver
    # g = webdriver.Chrome()
    # s = SetCookies(se).check_cookies()
    # work_path = os.path.dirname(os.path.dirname(__file__))
    # print(work_path)
